import React from 'react';
import { Empty, DotLoading, Toast } from 'antd-mobile';
import { motion } from 'framer-motion';
import { useSwipeable } from 'react-swipeable';
import ReactPlayer from 'react-player';
 
const VideoPlayer = ({ 
  currentVideo, 
  onSwipeUp, 
  onSwipeDown, 
  isFirstVideo, 
  isLastVideo, 
  isLoading, 
  isEmpty,
  onPlay = () => {},
  onPause = () => {},
  onEnded = () => {},
}) => {
  const [isPlaying, setIsPlaying] = React.useState(true);
  const [retryCount, setRetryCount] = React.useState(0);
  const maxRetries = 3;

  // Auto-play when video source changes and notify parent
  React.useEffect(() => {
    setIsPlaying(true);
    setRetryCount(0);
    onPlay();
  }, [currentVideo, onPlay]);

  // Handle manual play/pause toggle
  const togglePlay = () => {
    setIsPlaying(prev => {
      const newIsPlaying = !prev;
      if (newIsPlaying) {
        onPlay();
      } else {
        onPause();
      }
      return newIsPlaying;
    });
  };

  // Handle swipe gestures
  const handlers = useSwipeable({
    onSwipedUp: () => {
      if (!isLastVideo && !isLoading) {
        onSwipeDown();
      } else if (isLastVideo && !isLoading) {
        Toast.show({
          content: '加载更多...',
          position: 'bottom',
        });
        onSwipeDown();
      }
    },
    onSwipedDown: () => {
      if (!isFirstVideo) {
        onSwipeUp();
      } else {
        Toast.show({
          content: '已经是第一个视频了',
          position: 'top',
        });
      }
    },
    preventDefaultTouchmoveEvent: true,
    trackMouse: false
  });

  // Handle when a video finishes playing
  const handleVideoEnd = () => {
    setIsPlaying(false);
    onEnded();
  };

  // Handle video play errors with retry logic
  const handleVideoError = (e) => {
    console.error('视频播放错误:', e);
    
    // 检查是否是自动播放限制错误
    if (e && e.target && e.target.error && e.target.error.name === 'NotAllowedError') {
      console.log('检测到自动播放限制，将在用户交互后重试');
      
      // 如果重试次数未超过限制，则延迟重试
      if (retryCount < maxRetries) {
        setTimeout(() => {
          setRetryCount(prev => prev + 1);
          setIsPlaying(true);
        }, 1000 * (retryCount + 1)); // 递增延迟：1秒、2秒、3秒
      } else {
        console.log('达到最大重试次数，等待用户手动交互');
        // 静默处理，等待用户点击或其他交互
      }
      return;
    }
    
    // 其他错误则正常处理
    setIsPlaying(false);
    onPause();
  };

  // Render empty state
  if (isEmpty) {
    return (
      <div className="absolute inset-0 bg-black flex items-center justify-center" style={{ zIndex: 1 }}>
        <Empty
          image={<img src="https://gw.alipayobjects.com/zos/antfincdn/ZHrcdLPrvN/empty.svg" alt="empty" />}
          description="系统维护中，请稍后再试"
          className="text-white"
        />
      </div>
    );
  }

  // Render loading state
  if (isLoading && !currentVideo) {
    return (
      <div className="absolute inset-0 bg-black flex items-center justify-center" style={{ zIndex: 1 }}>
        <div className="text-center text-white">
          <div className="mb-[0.4rem] text-[0.32rem]">正在加载视频</div>
          <DotLoading color='white' />
        </div>
      </div>
    );
  }

  return (
    <div 
      {...handlers} 
      className="absolute inset-0 bg-black flex items-center justify-center"
      style={{ zIndex: 1 }}
    >
      {currentVideo ? (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.3 }}
          className="relative w-full h-full"
          onClick={togglePlay}
        >
          <ReactPlayer
            url={currentVideo.url} // Ensure we are using the url property
            playing={isPlaying}
            controls={false}
            width="100vw"
            height="calc(100vh - 1rem)"
            className="absolute inset-0"
            style={{ objectFit: 'contain', zIndex: 1 }}
            loop={true} // Disable loop to handle end of video
            volume={1}
            onPlay={onPlay}
            onPause={onPause}
            onEnded={handleVideoEnd}
            onError={handleVideoError}
            config={{
              file: {
                attributes: {
                  playsInline: true,
                }
              }
            }}
          />
          {isLoading && isLastVideo && (
            <div className="absolute right-0 left-0 bottom-[2rem] z-10 text-center text-white">
              <div className="flex justify-center items-center text-[0.28rem]">
              加载更多... <DotLoading color='white' />
              </div>
            </div>
          )}
        </motion.div>
      ) : (
        <div className="text-white text-[0.32rem]">加载中...</div>
      )}
    </div>
  );
};

export default VideoPlayer;
